package com.springboot.dubbo.config;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.MonitorConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.springboot.config.ProviderConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * dubbo配置工厂
 *
 * @author supu
 * @create 2019-01-04 17:22
 **/
@Configuration
public class DubboConfigFactory {
    private static final String NEED = "need";

    @Autowired
    private ProviderConfig providerConfig;

    @Bean
    public RegistryConfig registryConfig(){
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setAddress(providerConfig.getString(ProviderConfig.DUBBO_REGISTRY_ADDRESS));
        return registryConfig;
    }

    @Bean
    public MonitorConfig monitorConfig() {
        MonitorConfig monitorConfig = new MonitorConfig();
        monitorConfig.setAddress(providerConfig.getString(ProviderConfig.DUBBO_MONITOR_ADDRESS));
        return monitorConfig;
    }

    @Bean
    public ProtocolConfig protocolConfig(){
        ProtocolConfig protocolConfig = new ProtocolConfig();
        protocolConfig.setName(providerConfig.getString(ProviderConfig.DUBBO_PROTOCOL_NAME));
        protocolConfig.setPort(Integer.parseInt(providerConfig.getString(ProviderConfig.DUBBO_PROTOCOL_PORT)));
        return protocolConfig;
    }

    @Bean
    public ApplicationConfig providerApplicationConfig() {
        return getApplicationConfig(providerConfig.getString(ProviderConfig.DUBBO_APPLICATION_PROVIDER_NAME));
    }

    @Bean
    public ApplicationConfig consumerApplicationConfig() {
        return getApplicationConfig(providerConfig.getString(ProviderConfig.DUBBO_APPLICATION_CONSUMER_NAME));
    }

    private ApplicationConfig getApplicationConfig(String name){
        ApplicationConfig application = new ApplicationConfig();
        application.setEnvironment(providerConfig.getString(ProviderConfig.DUBBO_APPLICATION_ENVIRONMENT));
        application.setName(name);
        String isNeed = providerConfig.getString(ProviderConfig.DUBBO_MONITOR_ISNEED);
        if (StringUtils.isNotEmpty(isNeed) && NEED.equals(isNeed)) {
            application.setMonitor(monitorConfig());
        }
        return application;
    }
}
